// 云+数据库
let upbase = []
let db=wx.cloud.database()
// 云+数据库
import {
  http
} from '../../utils/http'
Page({
  data: {
    // 文件上传
    src:'',
    srcs:'',
    imgs: [],
    imgssub: [],
    count: 3,
    tabArr: {
      curHdIndex: 0,
      curBdIndex: 0
    },
    // 文件end
    active: 0,
    currentTab: 0,
    familishowModal: false,
    /* 家庭信息模态框 */
    familiModal: {
      title: '',
    },
    familyIdValue: '', //家庭信息单选框id
    lists: [], //家庭信息查询结果集
    ysx006idCard: '', // 家庭信息身份证号
    familyId: '', // 家庭信息id
    familyRole: '', // 家庭角色
    fName: '', // 姓名
    cardType: '', // 证件类型
    idCard: '', //证件号码
    birthday: '', // 出生日期
    sex: '', // 性别
    age: '', //年龄
    educationHistory: '', // 学历
    maritalStatus1: '', //婚姻状况
    healthStatus: '', //健康状况
    phone: '', //联系电话
    uInfoId: '', // 申请人ID
    // 家庭信息--家庭角色模块
    roleSelectDatas: ['户主', '配偶', '父母', '子女'], //下拉列表的数据
    shows: false, //控制下拉列表的显示隐藏，false隐藏、true显示
    indexs: 0, //默认选择的下拉列表下标,

    // 家庭信息--证件类型模块
    idType: ['居民身份证', '户口本', '士官证', '护照', '港澳通行证'],
    shows2: false,
    indexs2: 0, //默认选择的下拉列表下标,

    // 家庭信息--最高学历模块
    highestEducation: ['本科', '研究生', '大专', '中专/中等技校、高中', '初中', '小学以下'],
    shows3: false,
    indexs3: 0, //默认选择的下拉列表下标,

    // 家庭信息--婚姻状况模块
    marital: ['已婚', '未婚', '丧偶', '离异'],
    shows4: false,
    indexs4: 0,

    // 家庭信息--健康状况模块
    healthCondition: ['健康', '良好', '一般', '较差'],
    shows5: false,
    indexs5: 0,
    /* 财务情况 */
    
    idCard: "",
    ysx005: {
      total_household_assets: "",
      bank_loans: "",
      all_family: "",
      household_net_worth: "",
      amount_guaranteed: "",
      amount_guaranteed_externally: "",
      total_household_debt: "",
      all_family_loan: "",
      net_household: "",
      other_amount_guaranteed: "",
      net_household_income: "",
     
    },
  },
  //文件上传start
  tabFun: function(e){  
    //获取触发事件组件的dataset属性  
    var _datasetId=e.target.dataset.id;  
    var _obj={};  
    _obj.curHdIndex=_datasetId;  
    _obj.curBdIndex=_datasetId;  
    this.setData({  
      tabArr: _obj  
    });  
  },  
  //上传图片
  upimage() {
    let that = this
    wx.chooseImage({
      count: 3, //需要上传图片的数量
      sizeType: ['original'], //原图还是压缩图
      sourceType: ['album', 'camera'], //从相机还是库选择
      success(res) {
        console.log(res)
        // 将图片渲染到界面
        console.log(res.tempFilePaths)
        //将拿到的图片地址链接赋值
        that.setData({
          src: res.tempFilePaths
        })
      }
    })
  },
  //显示改图片
  viewimager() {
    let that = this
    wx.previewImage({
      current: '',
      urls: that.data.src,
    })


  },
   tabFun: function(e){  
    //获取触发事件组件的dataset属性  
    var _datasetId=e.target.dataset.id;  
    var _obj={};  
    _obj.curHdIndex=_datasetId;  
    _obj.curBdIndex=_datasetId;  
    this.setData({  
      tabArr: _obj  
    });  
  },  
  //将图片上传云
  imagecloud() {
    let that = this
    wx.showLoading({
      title: '上传中',
    })
    let time = Date.parse(new Date()) / 1000
    wx.cloud.uploadFile({
      cloudPath: '2022-9-23/' + time, //上传图片的名字
      filePath: that.data.src[0], // 图片的临时地址
    }).then(res => {
      wx.hideLoading()
      wx.showToast({
        title: '上传成功',
      })
      console.log(res.fileID, i)
      upbase[i] = res.fileID

    }).catch(error => {
      console.log(error)
    })

  },
  upbase(){
    console.log("upbase的值",upbase)
    db.collection("ImageData").add({
      data:{
      src:upbase
    }
    })
    .then(res=>{
      wx.showToast({
        title: '上传成功',
      })
     })
     .catch(err=>{
       console.log(err)
     }
      )
    
  },
  //显示上传到数据库的
  baseimage(){
    let that=this
    db.collection("ImageData").get()
    .then(res=>{
      that.setData({
        srcs:res.data
      })
    })
    console.log(that.data.srcs)
  },
  //文件上传end
  // 点击下拉显示框-家庭角色模块
  selectTaps() {
    this.setData({
      shows: !this.data.shows,
      shows2: false,
      shows3: false,
      shows4: false,
      shows5: false,
    });
  },
  // 点击下拉显示框-证件类型模块
  selectTaps2() {
    this.setData({
      shows: false,
      shows2: !this.data.shows2,
      shows3: false,
      shows4: false,
      shows5: false,
    });
  },
  // 点击下拉显示框-最高学历模块
  selectTaps3() {
    this.setData({
      shows: false,
      shows2: false,
      shows3: !this.data.shows3,
      shows4: false,
      shows5: false,
    });
  },
  // 点击下拉显示框-婚姻状况模块
  selectTaps4() {
    this.setData({
      shows: false,
      shows2: false,
      shows3: false,
      shows4: !this.data.shows4,
      shows5: false,
    });
  },
  // 点击下拉显示框-婚姻状况模块
  selectTaps5() {
    this.setData({
      shows: false,
      shows2: false,
      shows3: false,
      shows4: false,
      shows5: !this.data.shows4,
    });
  },

  // 点击下拉列表-家庭角色模块
  optionTaps(e) {
    let Indexs = e.currentTarget.dataset.index; //获取点击的下拉列表的下标
    console.log(Indexs)
    this.setData({
      indexs: Indexs,
      shows: !this.data.shows,
      shows2: false,
    });

  },
  // 点击下拉列表-证件类型模块
  optionTaps2(e) {
    let Indexs = e.currentTarget.dataset.index; //获取点击的下拉列表的下标
    // console.log(Indexs)
    this.setData({
      indexs2: Indexs,
      shows2: !this.data.shows2
    });
  },
  // 点击下拉列表-最高学历模块
  optionTaps3(e) {
    let Indexs = e.currentTarget.dataset.index; //获取点击的下拉列表的下标
    // console.log(Indexs)
    this.setData({
      indexs3: Indexs,
      shows3: !this.data.shows3
    });
  },
  // 点击下拉列表-婚姻状况模块
  optionTaps4(e) {
    let Indexs = e.currentTarget.dataset.index; //获取点击的下拉列表的下标
    // console.log(Indexs)
    this.setData({
      indexs4: Indexs,
      shows4: !this.data.shows4
    });
  },
  // 点击下拉列表-健康状况模块
  optionTaps5(e) {
    let Indexs = e.currentTarget.dataset.index; //获取点击的下拉列表的下标
    // console.log(Indexs)
    this.setData({
      indexs5: Indexs,
      shows5: !this.data.shows5
    });
  },


  switchNav: function (e) {
    var page = this;
    var id = e.target.id;
    if (this.data.currentTab == id) {
      return false;
    } else {
      page.setData({
        currentTab: id
      });
    }
    page.setData({
      active: id
    });
  },
  filterViewMove(e) {

    return false;
  },
  bindChange(e) {
    let id = e.detail.current
    this.setData({
      active: id
    });
    this.setData({
      currentTab: id
    });
  },

  /* 家庭信息模态框 */
  bindViewEvent: function (e) {
    app.process(this, e);
  },
  /**
   * 点击新增弹窗
   */
  showfamiliDialogBtn: function (e) {
    if (e.currentTarget.dataset.name == 'update') {
      if (this.data.familyIdValue != '') {
        let _that = this;
        this.setData({
          familiModal: {
            title: '更新'
          },
          familishowModal: true
        });
        console.log(this.data.familyIdValues)
        http.request({
          url: '/selectIdFamilyInfo',
          data: {
            //向后端传递的参数数据，记得后端要设置请求参数的注解
            familyId: this.data.familyIdValue
          },
          method: 'GET',
          header: {
            'content-type': 'application/json;charset=utf-8'
          },
          success(data) {
            // console.log(data.data.cardType)
            // console.log(data.data.educationHistory)
            var familyRoleIndex; // 家庭角色索引
            var cardTypeIndex; // 证件类型索引
            var educationHistoryIndex; // 最高学历索引
            var maritalStatusIndex; // 婚姻状况索引
            var healthStatusIndex; // 健康状况索引
            // 家庭角色
            for (let i = 0; i < _that.data.roleSelectDatas.length; i++) {
              if (_that.data.roleSelectDatas[i] == data.data.familyRole) {
                familyRoleIndex = i;
              }
            }
            // 证件类型
            for (let i = 0; i < _that.data.idType.length; i++) {
              if (_that.data.idType[i] == data.data.cardType) {
                cardTypeIndex = i;
              }
            }
            // 最高学历
            for (let i = 0; i < _that.data.highestEducation.length; i++) {
              if (_that.data.highestEducation[i] == data.data.educationHistory) {
                educationHistoryIndex = i;
              }
            }
            // 婚姻状况
            for (let i = 0; i < _that.data.marital.length; i++) {
              if (_that.data.marital[i] == data.data.maritalStatus) {
                maritalStatusIndex = i;
              }
            }
            // 健康状况
            for (let i = 0; i < _that.data.healthCondition.length; i++) {
              if (_that.data.healthCondition[i] == data.data.healthStatus) {
                healthStatusIndex = i;
              }
            }
            // 给lists数组赋值（返回的数组集合）
            _that.setData({
              familyId: data.data.familyId,
              indexs: familyRoleIndex,
              fName: data.data.fname,
              indexs2: cardTypeIndex,
              idCard: data.data.idCard,
              birthday: data.data.birthday,
              sex: data.data.sex,
              age: data.data.age,
              indexs3: educationHistoryIndex,
              indexs4: maritalStatusIndex,
              indexs5: healthStatusIndex,
              phone: data.data.phone,
              uinfoId: data.data.uInfoId,
            })
            if (data.data) {
              wx.hideLoading({
                success: (res) => {},
              })
            } else {}
          }
        });
      } else {
        wx.showToast({
          title: '请选择家庭成员',
          icon: 'error',
          mask: true,
          duration: 1500,
        })
      }


    } else {
      if (this.data.ysx006idCard != '') {
        this.setData({
          familiModal: {
            title: '新增'
          },
          familishowModal: true
        });
      } else {
        wx.showToast({
          title: '请输入身份证号!',
          icon: 'error',
          mask: true,
          duration: 1500,
        })
      }

    }
  },
  /**
   * 弹出框蒙层截断touchmove事件
   */
  preventfamiliTouchMove: function () {},
  /**
   * 隐藏模态对话框
   */
  hidefamiliModal: function () {
    this.setData({
      familishowModal: false
    });
  },
  /**
   * 对话框取消按钮点击事件
   */
  onfamiliCancel: function () {
    this.hidefamiliModal();
  },
  // 家庭信息模块--查询请求
  selectId(e) {
    if (this.data.ysx006idCard != '') {
      let _that = this;
      http.request({
        url: '/selectId',
        data: {
          //向后端传递的参数数据，记得后端要设置请求参数的注解
          idNumber: this.data.ysx006idCard
        },
        method: 'GET',
        header: {
          'content-type': 'application/json;charset=utf-8'
        },
        success(data) {
          console.log(this)
          // 给lists数组赋值（返回的数组集合）
          _that.setData({
            lists: data.data
          })
          if (data.data) {
            wx.hideLoading({
              success: (res) => {},
            })
          } else {}
        }
      })
    } else {
      wx.showToast({
        title: '请输入身份证号!',
        icon: 'error',
        mask: true,
        duration: 1500,
      })
    }

  },
  /**
   * 对话框确认按钮点击事件
   */
  onfamiliConfirm: function (e) {
    this.hidefamiliModal();
    // 需要判断是新增还是更改
    let _that = this;
    if (this.data.familiModal.title == '新增') {
      http.request({
        url: '/addFamilyInfo',
        data: {
          //向后端传递的参数数据，记得后端要设置请求参数的注解
          idNumber: this.data.ysx006idCard,
          familyRole: this.data.roleSelectDatas[this.data.indexs],
          fname: this.data.fName,
          cardType: this.data.idType[this.data.indexs2],
          idCard: this.data.idCard,
          birthday: this.data.birthday,
          sex: this.data.sex,
          age: this.data.age,
          educationHistory: this.data.highestEducation[this.data.indexs3],
          maritalStatus: this.data.marital[this.data.indexs4],
          healthStatus: this.data.healthCondition[this.data.indexs5],
          phone: this.data.phone,
        },
        method: 'POST',
        header: {
          'content-type': 'application/json;charset=utf-8'
        },
        success(data) {
          // 判断后端数据是否接收成功
          if (data.data) {
            wx.showToast({
              title: '保存成功!',
              icon: 'success',
              mask: true,
              duration: 500,
            })
            _that.selectId(e)
          } else {
            wx.showToast({
              title: `保存失败!`,
              icon: 'error',
              mask: true,
              duration: 1500,
            })
          }
        }
      })

    } else {

      http.request({
        url: '/editFamilyInfo',
        data: {
          //向后端传递的参数数据，记得后端要设置请求参数的注解
          familyId: this.data.familyId,
          idNumber: this.data.ysx006idCard,
          familyRole: this.data.roleSelectDatas[this.data.indexs],
          fname: this.data.fName,
          cardType: this.data.idType[this.data.indexs2],
          idCard: this.data.idCard,
          birthday: this.data.birthday,
          sex: this.data.sex,
          age: this.data.age,
          educationHistory: this.data.highestEducation[this.data.indexs3],
          maritalStatus: this.data.marital[this.data.indexs4],
          healthStatus: this.data.healthCondition[this.data.indexs5],
          phone: this.data.phone,
          uInfoId: this.data.uInfoId,
        },
        method: 'POST',
        header: {
          'content-type': 'application/json;charset=utf-8'
        },
        success(data) {
          console.log(this)
          // 判断后端数据是否接收成功
          if (data.data) {
            wx.showToast({
              title: '更新成功!',
              icon: 'success',
              mask: true,
              duration: 1500,
            })
            _that.selectId(e)
          } else {
            wx.showToast({
              title: `更新失败!`,
              icon: 'error',
              mask: true,
              duration: 1500,
            })
          }
        }
      })

    }

  },
  /**
   * 删除
   */
  deleteFamilyInfo(e) {
    if (this.data.familyIdValue != '') {
      let _that = this;
      http.request({
        url: '/deleteFamilyInfo',
        data: {
          //向后端传递的参数数据，记得后端要设置请求参数的注解
          familyId: this.data.familyIdValue
        },
        method: 'GET',
        header: {
          'content-type': 'application/json;charset=utf-8'
        },
        success(data) {
          console.log(this)
          if (data.data) {
            wx.showToast({
              title: '删除成功!',
              icon: 'success',
              mask: true,
              duration: 500,
            })
            _that.selectId(e)
          } else {
            wx.showToast({
              title: `删除失败!`,
              icon: 'error',
              mask: true,
              duration: 1500,
            })
          }
        }
      })
      this.setData({
        familyIdValue: ''
      });
      
    } else {
      wx.showToast({
        title: '请选择家庭成员!',
        icon: 'error',
        mask: true,
        duration: 1500,
      })
    }
  },
  /**
   * 复选框改变事件
   */
  checkboxChange(e) {
    this.data.familyIdValue = e.detail.value
  },
  // 根据身份证信息查找用户信用评级
  findCredit(e) {
    let _that = this
    http.request({
      url: '/findCreditByIdCard',
      data: {
        idCard: this.data.idCard
      },
      method: 'GET',
      header: {
        'content-type': 'application/json;charset=utf-8'
      },
      success(data) {
        console.log(data.data)
        if (data.data) {
          _that.setData({
            // 个人情况
            personMessageAge: data.data.personMessageAge,
            personMessageEdu: data.data.personMessageEdu,
            personMessageHealth: data.data.personMessageHealth,
            //家庭情况
            familyMessageMarry: data.data.familyMessageMarry,
            familyMessageFamilycount: data.data.familyMessageFamilycount,
            familyMessageAppraise: data.data.familyMessageAppraise,
            familyMessageHouse: data.data.familyMessageHouse,
            // 财务情况
            // financeMessage: data.data.financeMessage,
            financeMessageDebtratio: data.data.financeMessageDebtratio,
            financeMessageJzc: data.data.financeMessageJzc,
            financeMessageRj: data.data.financeMessageRj,
            financeMessageDw: data.data.financeMessageDw,
            // 职业情况
            // professionalMessage: data.data.financeMessageDebtratio,
            professionalMessageType: data.data.professionalMessageType,
            professionalMessageEconomic: data.data.professionalMessageEconomic,
            professionalMessageProspects: data.data.professionalMessageProspects,
            professionalMessageYear: data.data.professionalMessageYear,
            professionalMessageJobs: data.data.professionalMessageJobs,
            professionalMessageTitle: data.data.professionalMessageTitle,
            // 个人信用记录
            personalCredit: data.data.personalCredit,
            // 保险情况
            insuranceSituation: data.data.insuranceSituation,
            housingProvidentFund: data.data.housingProvidentFund,
            socialInsurance: data.data.socialInsurance,
            // 总分
            total_score: data.data.total_score,
          })

          wx.hideLoading({
            success: (res) => {},
          })
        } else {

        }
      }
    })
  },
  // 保存用户评级
  saveCredit(e) {
    let _that = this
    // debugger
    http.request({
      url: '/editCreditRating',

      data: {
        idCard: this.data.idCard,
        // 个人情况
        personMessageAge: this.data.personMessageAge,
        personMessageEdu: this.data.personMessageEdu,
        personMessageHealth: this.data.personMessageHealth,
        //家庭情况
        familyMessageMarry: this.data.familyMessageMarry,
        familyMessageFamilycount: this.data.familyMessageFamilycount,
        familyMessageAppraise: this.data.familyMessageAppraise,
        familyMessageHouse: this.data.familyMessageHouse,
        // 财务情况
        // financeMessage: data.data.financeMessage,
        financeMessageDebtratio: this.data.financeMessageDebtratio,
        financeMessageJzc: this.data.financeMessageJzc,
        financeMessageRj: this.data.financeMessageRj,
        financeMessageDw: this.data.financeMessageDw,
        // 职业情况
        // professionalMessage: data.data.financeMessageDebtratio,
        professionalMessageType: this.data.professionalMessageType,
        professionalMessageEconomic: this.data.professionalMessageEconomic,
        professionalMessageProspects: this.data.professionalMessageProspects,
        professionalMessageYear: this.data.professionalMessageYear,
        professionalMessageJobs: this.data.professionalMessageJobs,
        professionalMessageTitle: this.data.professionalMessageTitle,
        // 个人信用记录
        personalCredit: this.data.personalCredit,
        // 保险情况
        insuranceSituation: this.data.insuranceSituation,
        housingProvidentFund: this.data.housingProvidentFund,
        socialInsurance: this.data.socialInsurance,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json;charset=utf-8'
      },
      success(data) {
        if (data.data) {
          wx.showToast({
            title: '保存成功!',
            icon: 'success',
            mask: true,
            duration: 1000,
          })
          http.request({
            url: '/findCreditByIdCard',
            data: {
              idCard: this.data.idCard
            },
            method: 'GET',
            header: {
              'content-type': 'application/json;charset=utf-8'
            },
            success(data) {
              console.log(data.data)
              if (data.data) {
                _that.setData({
                  // 个人情况
                  personMessageAge: data.data.personMessageAge,
                  personMessageEdu: data.data.personMessageEdu,
                  personMessageHealth: data.data.personMessageHealth,
                  //家庭情况
                  familyMessageMarry: data.data.familyMessageMarry,
                  familyMessageFamilycount: data.data.familyMessageFamilycount,
                  familyMessageAppraise: data.data.familyMessageAppraise,
                  familyMessageHouse: data.data.familyMessageHouse,
                  // 财务情况
                  // financeMessage: data.data.financeMessage,
                  financeMessageDebtratio: data.data.financeMessageDebtratio,
                  financeMessageJzc: data.data.financeMessageJzc,
                  financeMessageRj: data.data.financeMessageRj,
                  financeMessageDw: data.data.financeMessageDw,
                  // 职业情况
                  // professionalMessage: data.data.financeMessageDebtratio,
                  professionalMessageType: data.data.professionalMessageType,
                  professionalMessageEconomic: data.data.professionalMessageEconomic,
                  professionalMessageProspects: data.data.professionalMessageProspects,
                  professionalMessageYear: data.data.professionalMessageYear,
                  professionalMessageJobs: data.data.professionalMessageJobs,
                  professionalMessageTitle: data.data.professionalMessageTitle,
                  // 个人信用记录
                  personalCredit: data.data.personalCredit,
                  // 保险情况
                  insuranceSituation: data.data.insuranceSituation,
                  housingProvidentFund: data.data.housingProvidentFund,
                  socialInsurance: data.data.socialInsurance,
                  // 总分
                  total_score: data.data.total_score,
                })

                wx.hideLoading({
                  success: (res) => {},
                })
              } else {

              }
            }
          })
          // setTimeout(()=>{
          //   wx.navigateTo({
          //     url: '/pages/home/home',
          //   })
          //  }, 1500)

        } else {
          wx.showToast({
            title: `保存失败!`,
            icon: 'error',
            mask: true,
            duration: 1500,
          })
        }

      }
    })
  },
  /* 检索校验 */
  inputCode: function (e) {
    let pwd = e.detail.value
    return pwd.replace(/[^\w\/]/ig, '')
  },
  /* 校验为数字 */
  inputNumber: function (e) {
    let pwd = e.detail.value
    return pwd.replace(/\D/g, '')
  },
  /*  财务状况-searchbysid */
  searchbysid() {
    let that = this
    http.request({
      url: '/findFinancialSituationByIdCard',
      method: "GET",
      data: {
        idCard: this.data.idCard
      },
      success(data) {
        if (!data.data) {
          wx.showToast({
            title: `没有数据`,
            icon: 'fail',
            mask: true,
            duration: 1500,
          })
          return;
        }
        that.setData({
          "ysx005": {
            total_household_assets: data.data.total_household_assets,
            bank_loans: data.data.bank_loans,
            all_family: data.data.all_family,
            household_net_worth: data.data.household_net_worth,
            amount_guaranteed: data.data.amount_guaranteed,
            amount_guaranteed_externally: data.data.amount_guaranteed_externally,
            total_household_debt: data.data.total_household_debt,
            other_loan: data.data.other_loan,
            all_family_loan: data.data.all_family_loan,
            net_household: data.data.net_household,
            other_amount_guaranteed: data.data.other_amount_guaranteed,
            net_household_income: data.data.net_household_income
          }
        })
      }
    })
  },



})